
type ValidatorCall = (value : any) => boolean | number | string | null | undefined;

export const createValidator = (valid : ValidatorCall | RegExp, msg ?: string) => {
	return (rule : any | any, value : any) => {
		if (typeof valid == "function" && valid(value)) {
			return Promise.resolve();
		} else if (valid instanceof RegExp && valid.test(value)) {
			return Promise.resolve(valid.test(value));
		}
		return Promise.reject(new Error(msg ?? "表单项验证失败"));
	}
}

// 图片正则
export const imageReg = /.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i;
// 判断是否为图片类型
export const isImage = (extension : string) => imageReg.test(extension);

// 图片校验器
export const imageValidator = createValidator(imageReg, "请填写正确的图片地址");

// 视频正则
export const videoRegex = /\.(mp4|avi|mov|mkv|webm)$/i;

export const isVideo = (filename : string) => videoRegex.test(filename);

// 视频校验器
export const videoValidator = createValidator(videoRegex, "请填写正确的视频地址");

// 数字带单位正则
export const numUnitReg = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?(px|rem|%?)$/;

// 数字正则
export const numberReg = /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;

//验证十进制数字
export const isNumber = (value : string | number) => numberReg.test(value.toString());


// 数字、百分比、带像素和包含选项 的校验器
export const numberOptionValidator = (options : any[], msg ?: string) => {
	return createValidator((value) => {
		return value.every((v : string) => numUnitReg.test(v) || options.findIndex(item => item.value.includes(v)) >= 0);
	}, msg ?? "请输入数字、百分比或选项中的值");
}